package com.qssoft.cqry.synchdb.pool;

import com.qssoft.cqry.synchdb.adapter.RedisMessageAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.util.Assert;

/**
 * @author liju.z
 */
@Slf4j
public class RedisMessagePool implements Runnable, SmartInitializingSingleton {

    private boolean destroy = false;

    private RedisMessageAdapter adapter;

    private String threadName;

    public RedisMessagePool(RedisMessageAdapter adapter, String threadName) {
        Assert.notNull(adapter, "RedisMessageAdapter is null");
        Assert.notNull(threadName, "thread name is null");
        this.adapter = adapter;
        this.threadName = threadName;
    }

    @Override
    public void run() {
        while (true) {
            if (destroy) break;
            try {
                adapter.getMessage(threadName);
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                log.error("线程执行失败...{}", e);
            }
        }
    }

    public void destroy() {
        destroy = true;
    }

    @Override
    public void afterSingletonsInstantiated() {
        new Thread(this, threadName).start();
    }
}
